//弹出对话框
function omnipotent(id, linkurl, title, close_type, w, h) {
    if (!w) w = 700;
    if (!h) h = 500;
    Wind.use("artDialog", "iframeTools", function () {
        art.dialog.open(linkurl, {
            id: id,
            title: title,
            width: w,
            height: h,
            lock: true,
            fixed: true,
            background: "#CCCCCC",
            opacity: 0,
            button: [{
                name: '确定',
                callback: function () {
                    if (close_type == 1) {
                        return true;
                    } else {
                        var d = this.iframe.contentWindow;
                        var form = d.document.getElementById('dosubmit');
                        form.click();
                    }
                    return false;
                },
                focus: true
            }]
        });
    });

}

/**
uploadid dialog id
name dialog名称
textareaid 最后数据返回插入的容器id
funcName 回调函数
controller 所属控制器
num 上传图片的数量
isPic 是否是图片上传
ext  上传格式
**/
function flashupload(uploadid, name, textareaid, funcName,  controller, num,isPic,ext) {
    console.log(uploadid, name, textareaid, funcName,  controller, num,isPic,ext)
 
    var setting = '&controller=' + controller + '&num=' + num+'&textareaid=' + textareaid +'&is_pic='+ isPic+'&ext='+ext ;
    var status = true;

    console.log(ROOT + '/index.php?a=swfupload&m=Admin&c=Upload'  + setting)
   
    if (status) {
        Wind.use("artDialog", "iframeTools", function () {
            art.dialog.open(ROOT + '/index.php?a=swfupload&m=Admin&c=Upload'  + setting, {
                title: name,
                id: uploadid,
                width: '650px',
                height: '420px',
                lock: true,
                fixed: true,
                background: "#CCCCCC",
                opacity: 0,
                ok: function () {
                    if (funcName) {
                        funcName.apply(this, [this, textareaid]);
                    } else {
                        submit_ckeditor(this, textareaid);
                    }
                },
                cancel: true
            });
        });
    }
}

//多图上传，SWF回调函数
function change_images(uploadid, returnid) {
    var d = uploadid.iframe.contentWindow;
    var in_content = d.$("#att-status").html().substring(1);
    var in_filename = d.$("#att-name").html().substring(1);
    var str = $('#' + returnid).html();
    var contents = in_content.split('|');
    var filenames = in_filename.split('|');
    $('#' + returnid + '_tips').css('display', 'none');
    if (contents == '') return true;
    $.each(contents, function (i, n) {
        var ids = parseInt(Math.random() * 10000 + 10 * i);
        var filename = filenames[i].substr(0, filenames[i].indexOf('.'));
        str += "<li id='image" + ids + "'><input type='text' name='" + returnid + "_url[]' value='" + n + "' style='width:310px;' ondblclick='image_priview(this.value);' class='input'> <input type='text' name='" + returnid + "_alt[]' value='" + filename + "' style='width:160px;' class='input' onfocus=\"if(this.value == this.defaultValue) this.value = ''\" onblur=\"if(this.value.replace(' ','') == '') this.value = this.defaultValue;\"> <a href=\"javascript:remove_div('image" + ids + "')\">移除</a> </li>";
    });

    $('#' + returnid).html(str);
}

//编辑器ue附件上传
function ueAttachment(uploadid, returnid) {
    var d = uploadid.iframe.contentWindow;
    var in_content = d.$("#att-status").html().substring(1);
    if (in_content == '') {
        return false;
    }
    in_content = in_content.split("|");
    var i;
    var in_filename = d.$("#att-name").html().substring(1);
    var filenames = in_filename.split('|');

    eval("var ue = editor" + returnid);

    for (i = 0; i < in_content.length; i++) {
        ue.execCommand('inserthtml', '<a href="' + in_content[i] + '" target="_blank">附件：' + filenames[i] + '</a>');
    }

}

//多文件上传回调
function change_multifile(uploadid, returnid) {
    var d = uploadid.iframe.contentWindow;
    var in_content = d.$("#att-status").html().substring(1);
    var in_filename = d.$("#att-name").html().substring(1);
    var str = '';
    var contents = in_content.split('|');
    var filenames = in_filename.split('|');
    $('#' + returnid + '_tips').css('display', 'none');
    if (contents == '') return true;
    $.each(contents, function (i, n) {
        var ids = parseInt(Math.random() * 10000 + 10 * i);
        var filename = filenames[i].substr(0, filenames[i].indexOf('.'));
        str += "<li id='multifile" + ids + "'><input type='text' name='" + returnid + "_fileurl[]' value='" + n + "' style='width:310px;' class='input'> <input type='text' name='" + returnid + "_filename[]' value='" + filename + "' style='width:160px;' class='input' onfocus=\"if(this.value == this.defaultValue) this.value = ''\" onblur=\"if(this.value.replace(' ','') == '') this.value = this.defaultValue;\"> <a href=\"javascript:remove_div('multifile" + ids + "')\">移除</a> </li>";
    });
    $('#' + returnid).append(str);
}

//缩图上传回调
function thumb_images(uploadid, returnid) {
    //取得iframe对象
    var d = uploadid.iframe.contentWindow;
    //取得选择的图片
    var in_content = d.$("#att-status").html().substring(1);
    if (in_content == '') return false;
    if (!IsImg(in_content)) {
        isalert('选择的类型必须为图片类型！');
        return false;
    }

    if ($('#' + returnid + '_preview').attr('src')) {
        $('#' + returnid + '_preview').attr('src', in_content);
    }
    $('#' + returnid).val(in_content);
}

//提示框 alert
function isalert(content, icon) {
    if (content == '') {
        return;
    }
    icon = icon || "error";
    Wind.use("artDialog", function () {
        art.dialog({
            id: icon,
            icon: icon,
            fixed: true,
            lock: true,
            background: "#CCCCCC",
            opacity: 0,
            content: content,
            cancelVal: '确定',
            cancel: true
        });
    });
}

//图片使用dialog查看
function image_priview(img) {


    if (img == '') {
        return;
    }
    filepath= ROOT+"/"+img;
    if (!IsImg(filepath)) {
          Wind.use('artDialog', function () {
            art.dialog({
                title: '预览',
                padding: 0,
                width: 230,
                height: 150,
                content: '<a href="' + filepath + '" target="_blank"><img src="'+PUBLIC+'/images/icon/down.gif"> 单击打开</a>',
                lock: true
            });
        });
        return false;
    }
    Wind.use('artDialog', 'imgready', function () {
            imgReady(filepath, function () {
                var width = 0,
                    maxWidth = 500,
                    maxHeight = 500,
                    height = 0;
                var hRatio;
                var wRatio;
                var Ratio = 1;
                var w = this.height;
                var h = this.width;
                wRatio = 500 / this.height;
                hRatio = 500 / this.width;

                if (maxWidth == 0) { //
                    if (hRatio < 1) Ratio = hRatio;
                } else if (maxHeight == 0) {
                    if (wRatio < 1) Ratio = wRatio;
                } else if (wRatio < 1 || hRatio < 1) {
                    Ratio = (wRatio <= hRatio ? wRatio : hRatio);
                }
                if (Ratio < 1) {
                    w = w * Ratio;
                    h = h * Ratio;
                }
                width = h;
                height = w;

                art.dialog({
                    title: '预览',
                    fixed: true,
                    width: width,
                    height: height,
                    id: "image_priview",
                    lock: true,
                    background: "#CCCCCC",
                    opacity: 0,
                    content: '<img src="' + filepath + '"  width="' + width + '" height="' + height + '" />'
                });

            });
        });
}

//添加/修改文章时，标题加粗
function input_font_bold() {
    if ($('#title').css('font-weight') == '700' || $('#title').css('font-weight') == 'bold') {
        $('#title').css('font-weight', 'normal');
        $('#style_font_weight').val('');
    } else {
        $('#title').css('font-weight', 'bold');
        $('#style_font_weight').val('bold');
    }
}

//移除相关文章
function remove_relation(sid, id) {
    var relation_ids = $('#relation').val();
    if (relation_ids != '') {
        $('#' + sid).remove();
        var r_arr = relation_ids.split('|');
        var newrelation_ids = '';
        $.each(r_arr, function (i, n) {
            if (n != id) {
                if (i == 0) {
                    newrelation_ids = n;
                } else {
                    newrelation_ids = newrelation_ids + '|' + n;
                }
            }
        });
        $('#relation').val(newrelation_ids);
    }
}

//显示相关文章
function show_relation(modelid, id) {
    $.getJSON(ROOT + "/index.php?a=public_getjson_ids&m=Content&g=Content&modelid=" + modelid + "&id=" + id, function (json) {
        var newrelation_ids = '';
        if (json.data == null) {
            isalert('没有添加相关文章！');
            return false;
        }
        $.each(json.data, function (i, n) {
            newrelation_ids += "<li id='" + n.sid + "'>·<span>" + n.title + "</span><a href='javascript:;' class='close' onclick=\"remove_relation('" + n.sid + "'," + n.id + ")\"></a></li>";
        });

        $('#relation_text').html(newrelation_ids);
    });
}

//图片上传回调
function submit_images(uploadid, returnid) {
    var d = uploadid.iframe.contentWindow;
    var in_content = d.$("#att-status").html().substring(1);
    var in_content = in_content.split('|');
    IsImg(in_content[0]) ? $('#' + returnid).attr("value", in_content[0]) : alert('选择的类型必须为图片类型');
}

//单文件上传回调
function submit_attachment(uploadid, returnid) {
    var d = uploadid.iframe.contentWindow;
    var in_content = d.$("#att-status").html().substring(1);
    var in_content = in_content.split('|');
    $('#' + returnid).attr("value", in_content[0]);
}

//移除ID
function remove_id(id) {
    $('#' + id).remove();
}

//输入长度提示
function strlen_verify(obj, checklen, maxlen) {
    var v = obj.value,
        charlen = 0,
        maxlen = !maxlen ? 200 : maxlen,
        curlen = maxlen,
        len = strlen(v);
    var charset = 'utf-8';
    for (var i = 0; i < v.length; i++) {
        if (v.charCodeAt(i) < 0 || v.charCodeAt(i) > 255) {
            curlen -= charset == 'utf-8' ? 2 : 1;
        }
    }
    if (curlen >= len) {
        $('#' + checklen).html(curlen - len);
    } else {
        obj.value = mb_cutstr(v, maxlen, true);
    }
}

//长度统计
function strlen(str) {
    return ($.browser.msie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}

function mb_cutstr(str, maxlen, dot) {
    var len = 0;
    var ret = '';
    var dot = !dot ? '...' : '';

    maxlen = maxlen - dot.length;
    for (var i = 0; i < str.length; i++) {
        len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
        if (len > maxlen) {
            ret += dot;
            break;
        }
        ret += str.substr(i, 1);
    }
    return ret;
}

//移除指定id内容
function remove_div(id) {
    $('#' + id).remove();
}

//转向地址
function ruselinkurl() {
    if ($('#islink').is(':checked') == true) {
        $('#linkurl').attr('disabled', null);
        return false;
    } else {
        $('#linkurl').attr('disabled', 'true');
    }
}

//验证地址是否为图片
function IsImg(url) {
    var sTemp;
    var b = false;
    var opt = "jpg|gif|png|bmp|jpeg";
    var s = opt.toUpperCase().split("|");
    for (var i = 0; i < s.length; i++) {
        sTemp = url.substr(url.length - s[i].length - 1);
        sTemp = sTemp.toUpperCase();
        s[i] = "." + s[i];
        if (s[i] == sTemp) {
            b = true;
            break;
        }
    }
    return b;
}

//验证地址是否为Flash
function IsSwf(url) {
    var sTemp;
    var b = false;
    var opt = "swf";
    var s = opt.toUpperCase().split("|");
    for (var i = 0; i < s.length; i++) {
        sTemp = url.substr(url.length - s[i].length - 1);
        sTemp = sTemp.toUpperCase();
        s[i] = "." + s[i];
        if (s[i] == sTemp) {
            b = true;
            break;
        }
    }
    return b;
}

//添加地址
function add_multifile(returnid) {
    var ids = parseInt(Math.random() * 10000);
    var str = "<li id='multifile" + ids + "'><input type='text' name='" + returnid + "_fileurl[]' value='' style='width:310px;' class='input'> <input type='text' name='" + returnid + "_filename[]' value='附件说明' style='width:160px;' class='input'> <a href=\"javascript:remove_div('multifile" + ids + "')\">移除</a> </li>";
    $('#' + returnid).append(str);
}




$(function () {

  // $("img").error(function(){
  //   $("img").replaceWith("<img id=demo1 src=" + ROOT + "/data/public/images/default.gif" + ">");
  // });
  // 
  // 

   layui.config({
      base: ROOT + '/lib/layuiadmin/' //静态资源所在路径
    }).extend({
      index: 'lib/index' //主入口模块
    }).use(['index', 'form', 'upload', 'laydate', 'laytpl'], function () {      
      var $ = layui.jquery, 
              laydate = layui.laydate, 
              layer = layui.layer, 
              upload = layui.upload,
              laydate = layui.laydate,
        laytpl = layui.laytpl;






      laydate.render({
        elem: '#laytime' //指定元素
      });

      // upload.render({
      //   elem: '.pic_upload'
      //   ,url: ROOT + '/index.php/Admin/Upload/do_upload.html'
      //   ,accept:'images'
      //   ,exts:'jpg|png|gif|bmp|jpeg'
      //   ,data:{
      //     is_pic:1,
      //     ext:'jpg|png|gif|bmp|jpeg'
      //   }
      //   ,before: function(obj){
      //     var item = this.item;
      //     //预读本地文件示例，不支持ie8
      //     obj.preview(function(index, file, result){
      //       $(item).parents('.pic_box').find('img').attr('src', result); //图片链接（base64）
            
      //     });
      //   }
      //   ,done: function(res){
      //     var item = this.item;
      //     //如果上传失败
      //     if(res.code > 0){
      //       return layer.msg('上传失败');
      //     }else{
      //       $(item).parents('.pic_box').find('#pic').attr('value', res.data.src); 
      //     }
      //     //上传成功
      //   }
      //   ,error: function(){
      //     //演示失败状态，并实现重传
      //     var demoText = $('#demoText');
      //     demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
      //     demoText.find('.demo-reload').on('click', function(){
      //       uploadInst.upload();
      //     });
      //   }
      // });


    /* 图片上传 */
    upload.render({
        elem: '.pic_upload'
        ,url: ROOT + '/index.php/Admin/Upload/do_upload.html'
        ,accept:'images'
        ,exts:'jpg|png|gif|bmp|jpeg'
        ,data:{
          is_pic:1,
          ext:'jpg|png|gif|bmp|jpeg'
        }
        ,method: 'post'
        ,before: function(input) {
            layer.msg('文件上传中...', {time:3000000});
        }
        ,done: function(res, index, upload) {

            var obj = $(this.item), 
                name = obj.attr('data-name');

                obj.prev().remove()

            if (res.code == 0) {
                obj.parents('ul').find('input.n').val(res.data.src)

            laytpl($('#J_PhotoTpl').html()).render({file: res.data.src, id:res.data.id, name:name}, function(html) {
         
                obj.before(html);
            });

                layer.msg('上传成功');
                return false;
            }
            
        }
    });



      
      //指定允许上传的文件类型
      upload.render({
        elem: '.file_upload'
        ,url: ROOT + '/index.php/Admin/Upload/do_upload.html'
        ,accept:'file'
        ,exts:'jpg|png|gif|bmp|jpeg|doc|zip|rar|7z'
        ,data:{
          is_pic:0,
          ext:'jpg|png|gif|bmp|jpeg|doc|zip|rar|7z'
        }

        ,done: function(res){
          var item = this.item;
          //如果上传失败
          if(res.code > 0){
            return layer.msg('上传失败');
          }else{
            $(item).parents('.file_box').find('#file').attr('value', res.data.src); 
          }
          //上传成功
        }
      });






    /* 相册上传 */
    upload.render({
        elem: '.pics_upload'
        ,url: ROOT + '/index.php/Admin/Upload/do_upload.html'
        ,accept:'images'
        ,exts:'jpg|png|gif|bmp|jpeg'
        ,data:{
          is_pic:1,
          ext:'jpg|png|gif|bmp|jpeg'
        }
        ,method: 'post'
        ,multiple: true
        ,before: function(input) {
            layer.msg('文件上传中...', {time:3000000});
        }
        ,done: function(res, index, upload) {

            var obj = $(this.item), 
                name = obj.attr('data-name');

            if (res.code == 0) {
            laytpl($('#J_PhotoTpl').html()).render({file: res.data.src, id:res.data.id, name:name}, function(html) {
             
                    obj.parents('.pics_box').find('.pics').find('ul').find('li.d').before(html);

                
            });

                layer.msg('上传成功');
                return false;
            }
            
        }
    });
    /* 删除相册 */
    $(document).on('click', '.feng-photo-delete', function() {
        var that = $(this);
        var url = $(that).attr('href')
        that.parents('ul').find('input.n').val('')
        that.parent('li').find('input').val('')
        that.parent('li').remove();
        // location.href = url;
        return false;
    });

    $('.pics_box').each(function(index, el) {
        if($(this).find('.n').val() == ''){
            $(this).find('li.s').hide();
        }
    });





      
    });






})